package com.wxsong.test.nacos.manage.controller;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Properties;

/**
 * 描述：
 *
 * @Author songweixing
 * @Date 2020/1/7
 */
@Controller
@RequestMapping("/configManage")
public class ConfigManageController {

    @RequestMapping("/index")
    public ModelAndView index(String dataId, String group, String serverAddr){
        ModelAndView mv = new ModelAndView("config/index");
        try {
            Properties properties = new Properties();
            properties.put("serverAddr", serverAddr);
            ConfigService configService = NacosFactory.createConfigService(serverAddr);
            String content = configService.getConfig(dataId, group, 5000);
            if(StringUtils.isEmpty(content)){
               content = "无";
            }
            mv.addObject("content", content);
            System.out.println(content);
        }catch (NacosException e){
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        return mv;
    }

    @RequestMapping("/publish")
    public ModelAndView publishConfig(String serverAddr, String dataId, String group, String content){
        ModelAndView mv = new ModelAndView("config/index");
        try {
            Properties properties = new Properties();
            properties.put("serverAddr", serverAddr);
            ConfigService configService = NacosFactory.createConfigService(properties);
            boolean isPublishOk = configService.publishConfig(dataId, group, content);
            System.out.println(isPublishOk);
            mv.addObject("publishMsg", isPublishOk ? "发布成功" : "发布失败");
        } catch (NacosException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        return mv;
    }
}
